/*
 * 创建日期 2006-9-21
 *
 * 更改所生成文件模板为
 * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
 */
package com.vanda.report.dp;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.commons.beanutils.PropertyUtils;

import com.vanda.report.ReportException;
import com.vanda.report.ReportInnerData;
import com.vanda.report.Validation;
import com.vanda.report.element.BeanElement;
/**
 * @author amway
 *
 * 更改所生成类型注释的模板为
 * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
 */
public class OrderElement extends BeanElement{
	private String field = null;

	public void validator() throws ReportException {
		Validation.checkRequired("OrderElement", "field", field);
		Validation.checkRequired("OrderElement","property",super.getProperty());
	}
	
	private class OrderComparator implements Comparator {
		private String[] orderFields = null;
		
		public OrderComparator(String[] fields){
			orderFields = fields;
		}
				
		public int compare(Object o1, Object o2) {
			Object detail1 = (Object) o1;
			Object detail2 = (Object) o2;
			
			try{
				for(int i=0;i<orderFields.length;i++){
					String[] sorts = getSortFieldAndFlag(orderFields[i]);
					int flag = Integer.parseInt(sorts[1]);
					
					String value1 = PropertyUtils.getProperty(detail1,sorts[0]).toString();
					String value2 = PropertyUtils.getProperty(detail2,sorts[0]).toString();
					
					int compare = value1.compareTo(value2);
					compare = compare * flag;
					if(compare == 0){
						continue;
					}
					return compare;
				}
			}catch(Exception e){
				e.printStackTrace();
			}
			return 0;
		}
	};

	
	/**
	 * 标签执行方法，递归执行
	 * @param obj
	 */
	public void execute(Object obj) throws ReportException{
		ReportInnerData reportData = (ReportInnerData)obj;
		String property = super.getProperty();
		
		try{
			//取得上下文数据
			Object contextObj = super.getNameObject(reportData);
			//取得order by的字段
			String[] fields = field.split(",");
			
			//取得需要排序的结果集
			List orderList = (List)super.getProperty(contextObj,property);
			
			//设置比较类
			OrderComparator comparator = new OrderComparator(fields);
			
			//排序
			Collections.sort(orderList,comparator);
			
			super.execute(obj);
		}catch(ReportException e){
			throw e;
		}catch(Exception e){
			throw new ReportException(e);
		}
	}
	
	private String[] getSortFieldAndFlag(String field){
		field = field.trim();
		String[] sorts = new String[2];
		String[] fields = field.split(" ");
		if(fields.length == 1){
			sorts[0] = field;
			sorts[1] = "1";
			return sorts;
		}
		sorts[0] = fields[0].trim();
		if(fields[1].trim().toLowerCase().equals("desc")){
			sorts[1] = "-1";
		}else{
			sorts[1] = "1";
		}
		
		return sorts;
	}
	/**
	 * @return
	 */
	public String getField() {
		return field;
	}

	/**
	 * @param string
	 */
	public void setField(String string) {
		field = string;
	}

}
